var xmlUpdateState = null;
var stateComplete;

function createXmlHttpRequest()
{
  if (window.XMLHttpRequest)
  {
    return new XMLHttpRequest();
  }
  else if (window.ActiveXObject)
  {
    return new ActiveXObject("Microsoft.XMLHTTP");
  }
  else
  {
    return null;
  }
}

function objectify(xmlElement)
{
	var children = xmlElement.childNodes;
	var index;
	var obj;
	var indexMap = new Object();

	for (index = 0; index < children.length; index++)
	{
		var child = children.item(index);

		if (child.nodeType == 3) // text
		{
			obj = child.nodeValue;
		}
		else if (child.nodeType == 1) // element
		{
			if (obj == undefined)
			{
				obj = new Object();
			}
			if(null == obj[child.baseName + "_Cnt"])
			{
				obj[child.baseName + "_Cnt"] = 1;
				obj[child.baseName] = objectify(child);
				obj[child.baseName + "_1"] = obj[child.baseName];
			}
			else
			{
				obj[child.baseName + "_Cnt"] = obj[child.baseName + "_Cnt"] + 1;
				obj[child.baseName + "_" + obj[child.baseName + "_Cnt"] ] = objectify(child);
			}
		}
	}

	return obj;
}

function updateState()
{
  if (xmlUpdateState == null)
  {
    xmlUpdateState = createXmlHttpRequest()
    if (xmlUpdateState == null)
    {
      return;
    }

    xmlUpdateState.open("GET", self.location.href, true);
    xmlUpdateState.onreadystatechange = handleUpdateState;
    xmlUpdateState.setRequestHeader("If-Modified-Since", new Date(0));
    xmlUpdateState.send();
  }
}

function handleUpdateState()
{
  if (xmlUpdateState.readyState == 4)
  {
    try
    {
      var response = xmlUpdateState.responseXML;
      var state = objectify(response.documentElement);

      stateComplete(state);
    }
    catch(expression)
    {
    }

    xmlUpdateState = null;
  }
}

function setStateCompletion(completion)
{
  stateComplete = new Function("state", completion + "(state);");
}

function readState(interval)
{
  setTimeout("updateState()", interval);
}
